﻿/**
*    @file:    usercontroller.cpp
*    @brief:
*    @author:  sanshi522@163.com
*    @date:    2024-11-03  14:57
*/
#include "usercontroller.h"
#include "user.h"

#include <QJsonDocument>
#include <qjwtutils.h>
#include <responesutils.h>
#include <userservice.h>

UserController::UserController(QObject *parent)
    : HttpController(parent)
{
}

UserController::~UserController()
{
}

void UserController::route(QString path, QString method, HttpRequest &request, HttpResponse &response)
{
    if (method == "GET")
    {
        if (path == "info")
        {
            return getUserInfo(request, response);
        }
        if (path == "list")
        {
            return getList(request, response);
        }
    }
    else if (method == "POST")
    {
        if (path.isEmpty())
        {
            return saveOne(request, response);
        }
    }
    else if (method == "PUT")
    {
        return saveOne(request, response, path.toULongLong());
    }
    else if (method == "DELETE")
    {
        return deleteOne(path.toULongLong(), response);
    }
}

void UserController::getUserInfo(HttpRequest &request, HttpResponse &response)
{
    QString authHeader = request.getHeader("Authorization");
    //权限找不到或者权限字符串头找不到
    if (authHeader.isEmpty() || authHeader.indexOf("Bearer ") == -1 || authHeader.split(" ").size() < 2)
    {
        qDebug() << "权限找不到或者权限字符串头找不到";
        ResponesUtils::unAuthorizedResponse(response);
        return;
    }
    QString token = authHeader.split(" ")[1];
    QJsonObject jsonObject = QJwtUtils::verifyAccessToken(token);
    User user;
    user.fromJsonObject(jsonObject);
    if (user.isEmpty())
    {
        ResponesUtils::unAuthorizedResponse(response);
        return;
    }
    qDebug() << __FUNCTION__ << user.toJsonObject();
    ResponesUtils::resultResponse(response, user.toJsonObject());
}

void UserController::getList(HttpRequest &request, HttpResponse &response)
{
    QVariantMap param;
    const QMultiMap<QByteArray, QByteArray> params = request.getParameterMap();
    QStringList deptIds;
    for (auto it = params.begin(); it != params.end(); it++)
    {
        if (it.key() == "deptIds[]")
        {
            deptIds.append(it.value());
            continue;
        }
        param.insert(it.key(), it.value());
    }
    param.insert("deptIds", deptIds.join(","));

    UserService objectService;
    QList<User> list;
    if (!objectService.getList(list, param))
    {
        return ResponesUtils::erroResponse(response, "数据库异常！");
    }

    QJsonArray jsonArray;
    for (auto &item : list)
    {
        jsonArray.append(item.toJsonObject());
    }
    if (param["page"].toULongLong() == 0 && param["pageSize"].toULongLong() == 0)
    {
        return ResponesUtils::resultResponse(response, jsonArray);
    }
    else
    {
        uint64_t total = 0;
        if (!objectService.getTotal(total, param))
        {
            return ResponesUtils::erroResponse(response, "数据库异常！");
        }
        return ResponesUtils::pagedResultResponse(response, total, jsonArray);
    }
}

void UserController::saveOne(HttpRequest &request, HttpResponse &response, uint64_t id)
{
    QByteArray body = request.getBody();
    QJsonParseError parseError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(body, &parseError);

    if (parseError.error != QJsonParseError::NoError)
    {
        return ResponesUtils::erroResponse(response, "请求参数JSON结构异常!");
    }
    User object;
    object.fromJsonObject(jsonDocument.object());
    if (id != 0)
    {
        object.setId(id);
    }
    UserService objectService;
    if (!objectService.saveOne(object, QBaseEntity::CustomProperty, jsonDocument.object().keys()))
    {
        return ResponesUtils::erroResponse(response, "数据库异常！");
    }
    //返回结果
    ResponesUtils::resultResponse(response, id == 0 ? "添加成功！" : "修改成功！");
}

void UserController::deleteOne(uint64_t id, HttpResponse &response)
{
    if (id == 0)
    {
        return ResponesUtils::erroResponse(response, "请指定删除ID！");
    }
    User object;
    object.setId(id);
    UserService objectService;
    if (!objectService.deleteOne(object))
    {
        return ResponesUtils::erroResponse(response, "数据库异常！");
    }
    //返回结果
    ResponesUtils::resultResponse(response, "删除成功！");
}
